// pages/login/login.js
var app = getApp();
var getInvite = require("../../mybehaviors/getInvite/getInvite");
var int = app.globalData.statusBarHeight * 2 + 40;
const menuButtonObject = wx.getMenuButtonBoundingClientRect().height;
const skinBehavior = require("../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [getInvite,skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: int + menuButtonObject,
    yzredirect: "",
    logintap: false,
    // 平台协议
    PlatformAgreement: '',
    openPlatformAgreement: false,
    tapSelectAgreement: true,
    agreement_name: '平台协议',
    // end
    // 兼容登录
    canIUseGetUserProfile:false,
    showAutoBindPhone: false, // 首次授权登录自动绑定手机号(PS：新会员！！！首次)
    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    AuthorizedPhone: '',
    // 余额
    balance:'余额',
    // 积分
    point:'积分'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.yzredirect = app.getyzredirect();
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }

    try {
      let showinfo = wx.getStorageSync("yz_basic_info");
      console.log(showinfo);
      this.setData({
        agreement_name: app._isTextEmpty(showinfo.home.register_setting.agreement_name) ? this.data.agreement_name : showinfo.home.register_setting.agreement_name,
        PlatformAgreement: showinfo.home.register_setting.new_agreement
      });
    } catch (error) {
      try {
        let showinfo = wx.getStorageSync("new_agreement");
        this.setData({
          agreement_name: app._isTextEmpty(showinfo.agreement_name) ? this.data.agreement_name : showinfo.agreement_name,
          PlatformAgreement: showinfo.new_agreement,
          themeStyle: `--themeBaseColor: ${showinfo.theme_color};`
        });
      } catch (error) {
        console.log(error);
      }
    }

  },
  PlatformAgreementTap() {
    this.setData({
      openPlatformAgreement: true
    });
  },
  PlatformAgreementClose() {
    this.setData({
      openPlatformAgreement: false
    });
  },
  PlatformAgreementOnChange(e) {
    this.setData({
      tapSelectAgreement: e.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  
  getUserProfileTap(e) {
    if(this.data.PlatformAgreement){
      if(!this.data.tapSelectAgreement){
        wx.showToast({
          title: '请勾选平台协议',
          duration:1000,
          icon:'none'
        });
        return;
      }
    }

    if (this.data.logintap) {
      // 正在请求 return
      console.log('正在请求');
      return;
    }
    this.setData({
      logintap: true
    });
    wx.showLoading({
      title: '登录中',
    });
    if(this.data.canIUseGetUserProfile){
      wx.getUserProfile({
        desc: '获取用户信息',
        success: (_info)=> {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': "",
            'gender': _info.userInfo.gender
          };
          console.log("info:", info);
          this.loginbtn(info);
        },fail:(err)=>{
          console.log(err)
          wx.hideLoading({
            success: (res) => {},
          });
        }
      });
    }else{
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': "",
        'gender': _info.userInfo.gender
      };
      console.log("info:兼容登录", info);
      this.loginbtn(info);
    }

  },
  loginbtn(_info) {
    console.log(this.data.logintap, '状态');
    var that = this;
    wx.login({
      success: (_json)=> {
        console.log(_info, _json.code,"login登录成功，获取用户info");
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2',
              app_type:'wechat',
              mini_version:'v1.1.141',
            },
            success: (res)=> {
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              var _data = res.data;
              console.log("登录接口", res);
              if (_data.result == 1) {
                try {
                  // 存储key
                  if (_data.data.user_info) {
                    wx.setStorageSync("nickname", _data.data.user_info.nickname);
                  }
                  if(_data.data.session){
                    wx.setStorageSync('session', _data.data.session);
                  }
                  if(_data.data.openid) {
                    wx.setStorageSync('openid', _data.data.openid);
                  }
                  if(_data.data.wx_token){
                    wx.setStorageSync('wx_token', _data.data.wx_token);
                  }
                  if(_info){
                    wx.setStorageSync('userInfo', _info);
                  }
                  if(_data.data.uid){
                    wx.setStorageSync('yz_uid', _data.data.uid);
                  }

                  wx.hideLoading();
                  if( _data.data.is_first_time_bind){
                    // 首次授权登录自动绑定手机号
                    that.setData({
                      showAutoBindPhone: true
                    });
                  }else{
                    that.getInviteData();
                  }

                  wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
                } catch (e) {
                  wx.reLaunch({
                    url: "/packageG/index/index",
                  });
                }

              } else {
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                    // if (res.confirm) {
                    // } else if (res.cancel) {
                    // }
                  }
                });
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: (res)=> {
              wx.hideLoading();
              wx.showToast({
                title: "第三方登录失败session、wx_token获取失败" + res.errMsg,
                duration:3000,
                icon:'none'
              });
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          this.setData({
            logintap: false
          });
          wx.showToast({
            title: "获取用户登录态失败！" + res.errMsg,
            duration:3000,
            icon:'none'
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: (res)=> {
        wx.hideLoading();
        this.setData({
          logintap: false
        });
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      }
    });
  },
  getInviteData() {
    this.getInvites();
  },
  //是否开启邀请页面
  getInvites() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data);
          } catch (e) {
            wx.reLaunch({
              url: "/packageG/index/index",
            });
          }

        }
        wx.hideLoading();
      },
      fail: (res)=> {
        console.log(res);
      },
    });
  },
  //初始化语言设置
  initLanguage() {
    let urlStr = app.getNetAddresss("setting.get-lang-setting");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            wx.setStorageSync("mailLanguage", JSON.stringify(data));
          } catch (e) {
            console.log(e);
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  // behaviors有相同处理函数
  // gotourl() {
  //   try {
  //     if (!this.data.yzredirect) {
  //       this.gomember();
  //     } else {
  //       if (this.data.yzredirect.indexOf("login/login") > 0) {
  //         this.gomember();
  //       } else {
  //         wx.reLaunch({
  //           url: "/" + this.data.yzredirect,
  //           fail:function(err){
  //             // 防止跳转不了 尝试直接指向会员中心
  //             wx.reLaunch({
  //               url: '/packageG/member_v2/member_v2',
  //             });
  //           }
  //         });
  //       }
  //     }
  //   } catch (e) {
  //     wx.reLaunch({
  //       url: "/packageG/index/index",
  //     });
  //   }
  // },

  gomember() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  // 获取授权手机号
  async getPhoneNumber(e) {
    let info = e.detail;
    if(info.errMsg == 'getPhoneNumber:ok') {
      let mobile = await this.getPhone_index(info.code);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInviteData();
    }else{
      this.getInviteData();
    }
  },
  getPhoneM() {
    return new Promise((resolve,reject) => {
      wx.checkSession({
        success: (res) => {
          console.log(res, 'checkSession');
          resolve();
        },
        fail:err => {
          reject(err);
        }
      });
    });
  },
  getSessionKey() {
    let key = wx.getStorageSync('session');
    console.log(key, '缓存的session');
    let urlStr = app.getNetAddresss('member.mini-decrypt.getSessionKey');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          session_key_id: key,
          not_validate_page: '0'
        },
        showToastIn: false,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res, '获取session_key');
            if (res.result == 1) {
              let keys = res.data.session_key_data.session_key;
              resolve(keys);
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  getPhone_index(info, keys) {
    wx.showLoading({
      title: '加载中',
    });
    // let arr = {
    //   info: info,
    //   session_key: keys
    // };
    let urlStr = app.getNetAddresss('member.member.miniMemberMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          code: info,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.phone_info.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => { },
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  setBindPhone(mobile){
    wx.hideLoading({
      success: (res) => { },
    });
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: this.data.AuthorizedPhone,
          mini_first_time_bind: 1
        },
        success: (resdata)=> {
          var res = resdata.data;
          
          if(this.data.changidInfo && this.data.changidInfo.change_uid){
            // 更新uid为合并后的会员id
            wx.setStorage({
              key: "yz_uid",
              data: this.data.changidInfo.change_uid,
            });
          }
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.getInviteData();
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  closeChangeId() {
    this.setData({
      showChangeID: false
    });
  },
  //先验证是否导致会员id变更
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile
        },
        validateBol: 2,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              wx.hideLoading({
                success: (res) => {},
              });
              let basic_info = wx.getStorageSync('yz_basic_info');
              this.setData({
                balance:basic_info.balance,
                point:basic_info.point,
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
});
